//
//  ViewController.m
//  StoreDataDemo
//
//  Created by holyen on 12-10-9.
//  Copyright (c) 2012年 holyen. All rights reserved.
//

#import "ViewController.h"
#import "UITextField+HideKeyBoard.h"
@interface ViewController ()

@end

@implementation ViewController
@synthesize dogs = _dogs;


- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.qqTextField hideKeyBoard:self.view];
    [self initUI];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (IBAction)buttonAction:(id)sender
{
    [self saveChanges];
}

- (void)initUI
{
    [self fetchDogsIfNecessary];
    self.nameTextField.text = [[_dogs objectAtIndex:0] name];
    self.ageTextField.text = [[_dogs objectAtIndex:0] age];
    self.sexTextField.text = [[_dogs objectAtIndex:0] sex];
    self.telTextField.text = [[_dogs objectAtIndex:0] tel];
    self.qqTextField.text = [[_dogs objectAtIndex:0] qq];
}

- (BOOL)saveChanges
{
    [self fetchDogsIfNecessary];
    [[_dogs objectAtIndex:0] setName:self.nameTextField.text];
    [[_dogs objectAtIndex:0] setAge:self.ageTextField.text];
    [[_dogs objectAtIndex:0] setSex:self.sexTextField.text];
    [[_dogs objectAtIndex:0] setTel:self.telTextField.text];
    [[_dogs objectAtIndex:0] setQq:self.qqTextField.text];
    
    return [NSKeyedArchiver archiveRootObject:_dogs toFile:[self dogsArchivePath]];
}

- (void)fetchDogsIfNecessary
{
    if (!_dogs) {
        NSString *path = [self dogsArchivePath];
        _dogs = [[NSKeyedUnarchiver unarchiveObjectWithFile:path] retain];
    }
    
    if (!_dogs) {
        _dogs = [[NSMutableArray alloc] init];
        [_dogs addObject:[[Dog alloc] init]];
    }
}

- (NSString *)dogsArchivePath
{
    return pathInDocumentDirectory(@"dogs.data");
}

- (void)dealloc {
    [_nameTextField release];
    [_ageTextField release];
    [_sexTextField release];
    [_telTextField release];
    [_qqTextField release];
    [_avatorImageView release];
    [super dealloc];
}
@end
